<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>交易系统界面</title>
  <!-- 使用 Bootstrap 来美化表格 -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <!-- 引入 ECharts 库 -->
  <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
  <style>
    /* 左中右布局样式 */
    .container {
      display: flex;
      height: 100vh;
    }
    .left-panel {
      flex: 3;
      padding: 20px;
      overflow-y: auto;
    }
    .middle-panel {
      flex: 6;
      padding: 20px;
      border-left: 1px solid #ccc;
      overflow-y: auto;
    }
    .right-panel {
      flex: 6;
      padding: 20px;
      border-left: 1px solid #ccc;
      overflow-y: auto;
    }
    /* 图表容器样式 */
    #chart-container {
      width: 100%;
      height: 400px;
    }
  </style>
</head>
<body>
<div class="container">
  <!-- 左边面板 -->
  <div class="left-panel">
    <h2 class="text-center">交易系统界面</h2>
    <!-- 其他查询创建内容 -->
    <div class="mb-3">
      <label for="accId" class="form-label">账户 ID</label>
      <input type="text" class="form-control" id="accId" placeholder="输入账户 ID">
      <label for="accountType" class="form-label">账户类型</label>
      <select class="form-select" id="accountType">
        <option value="">请选择</option>
        <option value="RT">实时系统</option>
        <option value="BACK_TRADE">回测系统</option>
      </select>
      <button class="btn btn-primary mt-2" id="queryAccountBtn">查询账户</button>
      <button class="btn btn-success mt-2" id="createAccountBtn">创建账户</button>
    </div>
  </div>
  <!-- 中间面板 -->
  <div class="middle-panel" id="middlePanelContent">
    <!-- 弹出框内容将动态显示在这里 -->
  </div>
  <!-- 右边面板 -->
  <div class="right-panel">
    <div id="chart-container"></div>
  </div>
</div>
<!-- 引入 Bootstrap JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
  document.getElementById('queryAccountBtn').addEventListener('click', function() {
    const accId = document.getElementById('accId').value;
    const accountType = document.getElementById('accountType').value;

    const queryAccAo = {
      accId: accId || null,
      accountType: accountType || null
    };

    // 调用账户查询接口
    fetch(`/trade/account/findAccount`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(queryAccAo)
    })
            .then(response => response.json())
            .then(data => {
              if (data.code === 200 && data.data.length > 0) {
                let accountInfo = '';
                data.data.forEach(account => {
                  let statusStr = '未运行';
                  let showBotton = '继续运行';
                  let opType = "START";
                  if (account.workerStatus === 'IN'){
                    statusStr = '运行中';
                    showBotton = '停止运行';
                    opType = "STOP";
                  }
                  accountInfo += `
            <p><strong>账户 ID:</strong> ${account.accId}</p>
            <p><strong>账户类型:</strong> ${account.tradeSystemType}</p>
            <p><strong>账户描述:</strong> ${account.accDesc}</p>
            <p><strong>账户状态:</strong> ${statusStr}</p>
            <p><strong>初始金额:</strong> ${account.initValue} 元</p>
            <p><strong>持仓价值:</strong> ${account.currentValue} 元</p>
            <p><strong>当前现金:</strong> ${account.currentCash} 元</p>
            <div>
              <button class="btn btn-danger" onclick="deleteAccount('${account.workerId}')">删除账户</button>
              <button class="btn btn-warning" onclick="opAccount('${account.workerId}', '${opType}')">${showBotton}</button>
              <button class="btn btn-info" onclick="viewReport('${account.accId}')">查看报告</button>
              <button class="btn btn-secondary" onclick="viewPositions('${account.accId}')">查看持仓</button>
            </div>
            <hr>
          `;
                });
                // 将内容显示在中间面板
                document.getElementById('middlePanelContent').innerHTML = accountInfo;
              } else {
                // 刷新左边内容
                // location.reload();
                // 查询结果为空，显示提示信息
                document.getElementById('middlePanelContent').innerHTML = '<p>未查询到结果</p>';
              }
            })
            .catch(error => {
              console.error('查询账户信息时出错:', error);
              alert('查询账户信息时出错，请稍后重试');
            });
  });

  document.getElementById('createAccountBtn').addEventListener('click', function() {
    // 显示创建账户表单
    let createAccountContent = `
      <h3>创建账户</h3>
      <form id="createAccountForm">
        <div>
          <label for="initValue">初始化金额:</label>
          <input type="text" id="initValue" name="initValue" required>
        </div>
        <div>
          <label for="accName">账户名称:</label>
          <input type="text" id="accName" name="accName" >
        </div>
        <div>
          <label for="desc">账户描述:</label>
          <input type="text" id="desc" name="desc">
        </div>
        <div>
          <label for="tradeMarketKey">市场类型:</label>
          <select id="tradeMarketKey" name="tradeMarketKey" required>
            <option value="A_GU">A股（T+1）</option>
            <option disabled value="A_GU_ETF">A股（T+0）</option>
            <option disabled value="QH">期货</option>
            <option disabled value="GG">港股</option>
            <option disabled value="MG">美股</option>
            <option disabled value="OKE">加密市场（欧意）</option>
            <option disabled value="BN">加密市场（币安）</option>
          </select>
        </div>
        <div>
          <label for="startTime">历史数据开始时间:</label>
          <input type="text" id="startTime" name="startTime" value="20250102000000">
        </div>
        <div>
          <label for="endTime">账户结束时间:</label>
          <input type="text" id="endTime" name="endTime">
        </div>
        <div>
          <label for="accType">账户类型:</label>
          <select id="accType" name="accType" required>
            <option value="RT">（实时）RT_TRADE_ACC</option>
            <option disabled value="BK_TRADE">（回测）BK_TRADE_ACC</option>
          </select>
        </div>
        <div>
          <label for="tradeSystemType">交易系统类型</label>
          <select id="tradeSystemType" name="tradeSystemType" required>
            <option value="RT">实时交易系统</option>
            <option disabled value="BACK_TRADE">回测系统</option>
          </select>
        </div>
        <div>
          <label for="frequency">数据频率</label>
          <select id="frequency" name="frequency" required>
            <option value="1d">1天</option>
            <option disabled value="100M">100毫秒</option>
            <option disabled value="1s">1秒</option>
            <option disabled value="30s">30秒</option>
            <option disabled value="1m">1分钟</option>
            <option disabled value="5m">5分钟</option>
            <option disabled value="10m">10分钟</option>
            <option disabled value="15m">15分钟</option>
            <option disabled value="60m">60分钟</option>
          </select>
        </div>
        <div>
          <label for="dataMarketType">市场数据类型</label>
          <select id="dataMarketType" name="dataMarketType" required>
            <option value="T1">T+1</option>
            <option value="T0">T+0</option>
          </select>
        </div>
         <div>
          <label for="strategy">市场数据类型</label>
          <select id="strategy" name="strategy" required>
            <option value="M45">量价5日线突破(普通版)</option>
          </select>
        </div>
        <div>
          <button disabled class="btn btn-warning" >选择目标</button>
        </div>
        <input type="submit" value="提交" class="col-12">
        <div>
          <label for="buyFeeRateGuo">买入，过户手续费:</label>
          <input type="text" id="buyFeeRateGuo" name="buyFeeRateGuo" value="0" size="10">
        </div>
        <div>
          <label for="buyFeeRateQuan">买入，券商手续费:</label>
          <input type="text" id="buyFeeRateQuan" name="buyFeeRateQuan" value="0" size="10">
        </div>
        <div>
          <label for="sellFeeRateQuan">卖出，券商手续费:</label>
          <input type="text" id="sellFeeRateQuan" name="sellFeeRateQuan" value="0" size="10">
        </div>
        <div>
          <label for="sellFeeRateYin">卖出，印花手续费:</label>
          <input type="text" id="sellFeeRateYin" name="sellFeeRateYin" value="0" size="10">
        </div>
        <div>
          <label for="sellFeeRateGuo">卖出，过户手续费:</label>
          <input type="text" id="sellFeeRateGuo" name="sellFeeRateGuo" value="0" size="10">
        </div>
        <div>
          <label for="buyFixedFee">买入，固定手续费:</label>
          <input type="text" id="buyFixedFee" name="buyFixedFee" value="0" size="10">
        </div>
        <div>
          <label for="sellFixedFee">卖出，固定手续费:</label>
          <input type="text" id="sellFixedFee" name="sellFixedFee" value="0" size="10">
        </div>
        <div>
          <label for="feeRateAround">手续费小数点:</label>
          <input disabled type="text" id="feeRateAround" name="feeRateAround" value="1000000">
        </div>
         <div>
          <label for="priceAround">金额小数点位数:</label>
          <input type="text" id="priceAround" name="priceAround" value="2" size="10">
        </div>
        <div>
          <label for="numAround">最少交易数量:</label>
          <input type="text" id="numAround" name="numAround" value="100" size="10">
        </div>
      </form>
    `;
    // 将内容显示在中间面板
    document.getElementById('middlePanelContent').innerHTML = createAccountContent;

    // 监听表单提交事件
    document.getElementById('createAccountForm').addEventListener('submit', function(e) {
      e.preventDefault();

      const formData = new FormData(this);
      const data = {};
      formData.forEach((value, key) => {
        data[key] = value;
      });

      // 向 /trade/account/createAccount 发起 POST 请求
      fetch('/trade/account/createAccount', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      })
              .then(response => response.json())
              .then(result => {
                if (result.code === 200) {
                  console.log('Success:', result);
                  alert('提交成功');
                } else {
                  console.error('Error:', result);
                  alert('提交失败: ' + result.message);
                }
              })
              .catch(error => {
                console.error('Error:', error);
                alert('提交失败，请稍后重试');
              });
    });
  });

  function deleteAccount(workerId) {
    if (confirm(`确定要删除账户 ${workerId} 吗？`)) {
      // 这里需要替换为实际的删除账户接口
      fetch(`/trade/account/deleteAccount/${workerId}`, {
        method: 'GET'
      })
              .then(response => response.json())
              .then(data => {
                if (data.code === 200) {
                  alert('账户删除成功');
                  // 刷新页面或更新右边面板内容
                  location.reload();
                } else {
                  alert('账户删除失败: ' + data.message);
                }
              })
              .catch(error => {
                console.error('删除账户时出错:', error);
                alert('删除账户时出错，请稍后重试');
              });
    }
  }

  function opAccount(workerId, opType) {
    let opMsg = "";
    if (opType === 'STOP'){
      opMsg = "停止";
    }
    if (opType === 'START'){
      opMsg = "启动";
    }

    if (confirm(`确定要${opMsg}账户运行吗？`)) {
      // 这里需要替换为实际的停止账户运行接口
      fetch(`/trade/account/opAccount/${workerId}/${opType}`, {
        method: 'GET'
      })
              .then(response => response.json())
              .then(data => {
                if (data.code === 200) {
                  alert('账户操作运行成功');
                  // 刷新页面或更新右边面板内容
                  location.reload();
                } else {
                  alert('账户停止运行失败: ' + data.message);
                }
              })
              .catch(error => {
                console.error('停止账户运行时出错:', error);
                alert('停止账户运行时出错，请稍后重试');
              });
    }
  }

  function viewReport(accId) {
    // 向 /front/report/{accId} 发起 GET 请求获取报告数据
    fetch(`/trade/report/getAcc/${accId}`)
            .then(response => response.json())
            .then(data => {
              if (data.code === 200) {
                const reports = data.data;
                // 初始化 ECharts 实例
                const chartDom = document.getElementById('chart-container');
                const myChart = echarts.init(chartDom);

                // 准备图表数据
                const xData = reports.map(report => report.reportTime16);
                const yData = reports.map(report => report.totalValue);

                // 配置图表选项
                const option = {
                  tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                      type: 'cross',
                      crossStyle: {
                        color: '#999'
                      }
                    },
                    formatter: function (params) {
                      const report = reports[params[0].dataIndex];
                      return `
                <p><strong>报告时间:</strong> ${report.reportTime16}</p>
                <p><strong>总价值:</strong> ${report.totalValue}</p>
                <p><strong>利润率:</strong> ${report.profitRate}%</p>
                <p><strong>回撤率:</strong> ${report.drawDown}</p>
                <p><strong>夏普比率:</strong> ${report.sharpRatio}</p>
                <p><strong>胜率:</strong> ${report.winRate}</p>
              `;
                    }
                  },
                  grid: {
                    left: '15%' // 调整图表左边距，让图表整体右移，可根据实际情况调整该值
                  },
                  xAxis: {
                    type: 'category',
                    data: xData,
                    axisLabel: {
                      rotate: 45, // 旋转 x 轴标签，防止重叠
                      interval: 'auto'
                    }
                  },
                  yAxis: {
                    type: 'value'
                  },
                  series: [{
                    data: yData,
                    type: 'line',
                    smooth: true // 使折线平滑
                  }]
                };

                // 使用刚指定的配置项和数据显示图表。
                myChart.setOption(option);
              } else {
                alert('获取报告数据失败: ' + data.message);
              }
            })
            .catch(error => {
              console.error('查看报告时出错:', error);
              alert('查看报告时出错，请稍后重试');
            });
  }

  // 新增查看持仓函数
  function viewPositions(accId) {
    const queryData = {
      accId: accId
    };
    fetch('/trade/account/findAccPos', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(queryData)
    })
            .then(response => response.json())
            .then(data => {
              if (data.code === 200 && data.data.length > 0) {
                let table = `
          <table class="table table-striped">
            <thead>
              <tr>
                <th>代码</th>
                <th>名称</th>
                <th>持有总数</th>
                <th>当前价格</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
        `;
                data.data.forEach(position => {
                  table += `
            <tr>
              <td>${position.tsCode}</td>
              <td>${position.targetName}</td>
              <td>${position.numTotal}</td>
              <td>${position.nowPrice}</td>
              <td>
                <button class="btn btn-info" onclick="sellPosition('${accId}', '${position}')">卖出</button>
              </td>
            </tr>
          `;
                });
                table += `
            </tbody>
          </table>
        `;
                document.getElementById('middlePanelContent').innerHTML = table;
              } else {
                alert('未查询到持仓信息');
              }
            })
            .catch(error => {
              console.error('查询持仓信息时出错:', error);
              alert('查询持仓信息时出错，请稍后重试');
            });
  }

  // 新增删除持仓函数
  function sellPosition(accId, position) {
    if (confirm(`确定要卖出持仓 ${position.targetName} 吗？`)) {
      fetch(`/trade/sell/${accId}/${position.tsCode}`, {
        method: 'GET'
      })
              .then(response => response.json())
              .then(data => {
                if (data.code === 200) {
                  alert('持仓卖出成功');
                  // 刷新持仓信息
                  const accId = document.getElementById('accId').value;
                  viewPositions(accId);
                } else {
                  alert('持仓卖出失败: ' + data.message);
                }
              })
              .catch(error => {
                console.error('卖出持仓时出错:', error);
                alert('卖出持仓时出错，请稍后重试');
              });
    }
  }
</script>
</body>
</html>